//
//  YSGHelpCenterCategoryCell.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/11/19.
//  Copyright © 2020 QDSG. All rights reserved.
//

import UIKit

protocol YSGHelpCenterCategoryCellDelegate: NSObjectProtocol {
    func categoryCell(didSelectedWith vm: YSGHelpCenterCategoryItemViewModel)
}

class YSGHelpCenterCategoryCell: UITableViewCell {
    
    weak var delegate: YSGHelpCenterCategoryCellDelegate?
    
    private var viewModel: YSGHelpCenterCategoryViewModel? {
        didSet {
            collectionView.reloadData()
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        makeUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        makeUI()
    }
    
    func makeUI() {
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
    }
    
    func configure(with vm: YSGHelpCenterCategoryViewModel) {
        collectionView.collectionViewLayout = vm.flowLayout()
        viewModel = vm
    }
    
    @IBOutlet private weak var bgView: UIView! {
        didSet {
            bgView.layer.cornerRadius = 16.0
            bgView.clipsToBounds = true
        }
    }

    @IBOutlet private weak var collectionView: UICollectionView! {
        didSet {
            collectionView.backgroundColor = .clear
            collectionView.contentInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 16)
            collectionView.delegate = self
            collectionView.dataSource = self
            collectionView.register(YSGHelpCenterCategoryItemCell.nibForCell(),
                                    forCellWithReuseIdentifier: YSGHelpCenterCategoryItemCell.reuseIdentifier())
        }
    }
    
}

extension YSGHelpCenterCategoryCell: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.numberOfRow ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YSGHelpCenterCategoryItemCell.reuseIdentifier(), for: indexPath) as! YSGHelpCenterCategoryItemCell
        
        if let vm = viewModel?.viewModel(at: indexPath) {
            cell.configure(with: vm)
        }
        
        return cell
    }
}

extension YSGHelpCenterCategoryCell: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let vm = viewModel?.viewModel(at: indexPath) else { return }
        delegate?.categoryCell(didSelectedWith: vm)
    }
}
